<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <!--      <el-form-item label="店铺归属平台id" prop="platformId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.platformId"-->
      <!--          placeholder="请输入店铺归属平台id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="平台" prop="platformId">
        <el-select v-model="queryParams.platformId" placeholder="请选择平台" clearable @change="handleQuery">
          <el-option label="全部" :value="0"/>
          <el-option
            v-for="item in platformsList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:merchants:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:merchants:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:merchants:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:merchants:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="merchantsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商家ID，主键自增" align="center" prop="id"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="头像" align="center" prop="avatarUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatarUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address"/>

      <el-table-column label="经纬度" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.location">
              经度: {{ scope.row.location.x }}<br/>
              纬度: {{ scope.row.location.y }}
            </span>
          <span v-else>无数据</span>
        </template>
      </el-table-column>


      <el-table-column label="联系电话" align="center" prop="contactPhone"/>
            <el-table-column label="所属平台" align="center" prop="platformId"/>
      <el-table-column label="所属平台" align="center">
        <template #default="{row}">
          {{ platformMap[row.platformId] || '未知平台' }}
        </template>
      </el-table-column>
      <el-table-column label="商家状态" align="center" prop="status">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '已停用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="最后更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:merchants:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:merchants:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCreateActivity(scope.row)"
            v-hasPermi="['system:merchants:edit']"
          >创建活动
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商家信息，存储所有参与霸王餐活动的商家信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="头像" prop="avatarUrl">
          <image-upload v-model="form.avatarUrl"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
        </el-form-item>

        <el-form-item label="小程序跳转地址" prop="miniProgramAddress">
          <el-input v-model="form.miniProgramAddress" placeholder="请输入小程序跳转地址"/>
        </el-form-item>

        <!-- 表单中的平台选择 -->
        <el-form-item label="店铺归属平台" prop="platformId">
          <el-select
            v-model="form.platformId"
            placeholder="请选择平台"
            clearable
          >
            <el-option
              v-for="item in platformsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="推广人id" prop="promoterId">
          <el-input v-model="form.promoterId" placeholder="请输入推广人id"/>
        </el-form-item>
        <el-form-item label="位置" required>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input
                v-model="form.location.x"
                placeholder="请输入经度 (x)"
              />
            </el-col>
            <el-col :span="12">
              <el-input
                v-model="form.location.y"
                placeholder="请输入纬度 (y)"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改商家活动，存储商家发布的霸王餐活动信息对话框 -->
    <el-dialog :title="activity_title" :visible.sync="open_activity" width="500px" append-to-body>
      <el-form ref="activityForm" :model="activityForm" :rules="activityRules" label-width="80px">
        <el-form-item label="活动关联商户" prop="merchantId">
          <el-input v-model="activityForm.merchantId" placeholder="请输入活动关联商户" />
        </el-form-item>
        <el-form-item label="活动名称" prop="activityTitle">
          <el-input v-model="activityForm.activityTitle" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="activityForm.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="activityForm.startTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="activityForm.endTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最大参与人数" prop="maxParticipants">
          <el-input v-model="activityForm.maxParticipants" placeholder="请输入最大参与人数" />
        </el-form-item>
        <el-form-item label="满减要求" prop="minOrderAmount">
          <el-input v-model="activityForm.minOrderAmount" placeholder="请输入满减要求" />
        </el-form-item>
        <el-form-item label="满减优惠" prop="discountAmount">
          <el-input v-model="activityForm.discountAmount" placeholder="请输入满减优惠" />
        </el-form-item>

        <el-form-item label="参与费用" prop="participatePrice">
          <el-input v-model="activityForm.participatePrice" placeholder="请输入具体费用" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitActivityForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>




</template>




<script>
import {listMerchants, getMerchants, delMerchants, addMerchants, updateMerchants} from "@/api/system/merchants"
import {listPlatforms} from "@/api/system/platforms"
import {addActivity} from "@/api/system/activity";

export default {
  name: "Merchants",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //平台信息
      platformsList: [],
      platformMap: {},
      // 总条数
      total: 0,
      // 商家信息，存储所有参与霸王餐活动的商家信息表格数据
      merchantsList: [],
      // 弹出层标题
      title: "",
      activity_title: "",
      // 是否显示弹出层
      open: false,
      open_activity: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        contactPhone: null,
        platformId: 0,
      },
      // 表单参数
      form: {
        location: {
          x: null,
          y: null
        },
      },
      activityForm: {
        merchantId: null,
        activityTitle: null,
        description: null,
        startTime: null,
        endTime: null,
        maxParticipants: null,
        minOrderAmount: null,
        discountAmount: null,
        participatePrice: null,
      },
      // 添加活动表单的验证规则
      activityRules: {
        title: [
          { required: true, message: "活动名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        minOrderAmount: [
          { required: true, message: "满减要求不能为空", trigger: "blur" }
        ],
        discountAmount: [
          { required: true, message: "满减优惠不能为空", trigger: "blur" }
        ]
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "地址不能为空", trigger: "blur"}
        ],
        'location.x': [{required: true, message: "经度不能为空", trigger: "blur"}],
        'location.y': [{required: true, message: "纬度不能为空", trigger: "blur"}],
        activityFee: [
          {required: true, message: "参与费用不能为空", trigger: "blur"}
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getListPlatform()
  },
  methods: {
    /** 查询平台信息 **/
    getListPlatform() {
      this.loading = true
      listPlatforms(this.queryParams).then(response => {
        this.platformsList = response.rows
        this.platformMap = response.rows.reduce((map, item) => {
          map[item.id] = item.name;
          return map;
        }, {});
        this.total = response.total
        this.loading = false
      })
    },


    /** 查询商家信息，存储所有参与霸王餐活动的商家信息列表 */
    getList() {
      this.loading = true
      listMerchants(this.queryParams).then(response => {
        this.merchantsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        avatarUrl: null,
        address: null,
        location: {
          x: null,
          y: null
        },
        contactPhone: null,
        activityFee: null,
        miniProgramAddress: null,
        platformId: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        operatorId: null,
        promoterId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商家信息，存储所有参与霸王餐活动的商家信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMerchants(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改商家信息，存储所有参与霸王餐活动的商家信息"
      })
    },
    //活动创建
    handleCreateActivity(row) {
      const id = row.id || this.ids
      this.activityForm = {
        merchantId: id,  // 这里确保正确设置了商家ID
        title: null,
        description: null,
        startTime: null,
        endTime: null,
        maxParticipants: null,
        minOrderAmount: null,
        discountAmount: null
      };
      this.open_activity = true;
      this.activity_title = "创建活动";
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMerchants(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMerchants(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    submitActivityForm() {
      this.$refs["activityForm"].validate(valid => {
        if (valid) {
          addActivity(this.activityForm).then(response => {
            this.$modal.msgSuccess("活动创建成功");
            this.open_activity = false;
            // 如果需要刷新列表可以在这里调用
          }).catch(error => {
            this.$modal.msgError("活动创建失败");
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商家信息，存储所有参与霸王餐活动的商家信息编号为"' + ids + '"的数据项？').then(function () {
        return delMerchants(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/merchants/export', {
        ...this.queryParams
      }, `merchants_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
